package main

import (
	"fmt"
	"gin_study_blog/common"
	"gin_study_blog/core"
	"gin_study_blog/models"
	"gorm.io/gorm"
)

func main() {
	// 读取配置文件
	core.YamlInitConfig()
	// 初始化日志
	common.Log = core.InitLogger()
	// 连接数据库
	common.DB = core.InitGorm()
	FindArticleCommentList("XMwegYsBWI-5VzaLQuke")
}

func FindArticleCommentList(articleID string) {
	// 先把文章下的根评论查出来
	var RootCommentList []models.CommentModel
	common.DB.Find(&RootCommentList, "article_id = ? AND parent_comment_id is null", articleID)
	// 遍历评论, 递归查评论下的所有评论
	for _, model := range RootCommentList {
		var subCommentList []models.CommentModel
		FindSubComment(model, &subCommentList)
		model.SubComments = subCommentList
	}
	fmt.Println(RootCommentList)
}

// FindSubComment 递归查评论下的子评论
func FindSubComment(model models.CommentModel, subCommentList *[]models.CommentModel) {
	err := common.DB.Preload("SubComments").Take(&model).Error
	if err == gorm.ErrRecordNotFound {
		// 没有记录
		return
	}
	for _, sub := range model.SubComments {
		*subCommentList = append(*subCommentList, sub)
		FindSubComment(sub, subCommentList)
	}
	return
}
